from typing import TypeVar, Generic, Optional
from datetime import datetime
from pydantic import BaseModel, Field
from fastapi import HTTPException

# 范性
T = TypeVar("T")


class BaseResponse(BaseModel, Generic[T]):
    """正常返回封装类 

    Args:
        BaseModel (_type_): _description_
        Generic (_type_): 返回数据类型

    Returns:
        _type_: _description_
    """
    code: int = 200
    msg: str = "success"
    data: Optional[T] = None

    @classmethod
    def success(cls, data: T = None, msg: str = "success"):
        return cls(code=200, msg=msg, data=data)
    
    @classmethod
    def error(cls, code: int = 500, msg: str = "error"):
        return cls(code=code, msg=msg)
    

class CustomException(HTTPException):
    """自定义异常
    用户请求中raise 异常中断请求配合异常捕获  返回规范的数据格式
    Args:
        HTTPException (_type_): _description_
    """
    def __init__(self, code: int = 200, msg: str = "error"):
        # 返回hhttp 状态码为200 代表请求正常； detail 按照正常封装类格式返回
        super().__init__(status_code=200, detail={"code": code, "msg": msg})


class PageResponse(BaseModel, Generic[T]):
    total: int = Field(..., deprecated="总数")
    data: Optional[T] = None